package com.bc.bcapi.service;

import com.bc.bcapi.dao.*;
import com.bc.bcapi.utils.web3j.Util;
import com.bc.bcmodel.domain.*;
import com.bc.commonentity.common.DBContextDbType;
import com.bc.commonentity.common.DBContextHolder;
import com.bc.commonentity.common.JsonResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;

@Service
public class ISTService {
    @Resource
    T_Wallet_infoMapper t_wallet_infoMapper;
    @Resource
    T_User_walletMapper t_user_walletMapper;

    @Transactional(rollbackFor = {
            Exception.class}, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public void payIST(String user_id, BigDecimal amount) throws Exception {
        String contract = Util.getISTID();
        DBContextHolder.setDbType(DBContextDbType.Master.name());
        HashMap<String, Object> userWalletMap = new HashMap<>();
        userWalletMap.put("user_id", user_id);
        userWalletMap.put("contract_id", contract);
        T_User_walletModel t_user_walletModel = t_user_walletMapper.getWalletByUid(user_id);
        if (t_user_walletModel == null) throw new Exception("not exist user wallet");
        T_Wallet_infoModel exist_wallet_infoModel = t_wallet_infoMapper.selectForUpdate(userWalletMap);
        if (exist_wallet_infoModel != null) {
            HashMap<String, Object> updateWalletMap = new HashMap<>();
            updateWalletMap.put("id", exist_wallet_infoModel.getId());
            updateWalletMap.put("amount", amount);
            t_wallet_infoMapper.recharge(updateWalletMap);
        } else {
            T_Wallet_infoModel new_wallet_info = new T_Wallet_infoModel();
            new_wallet_info.setUser_id(user_id);
            new_wallet_info.setContract_id(contract);
            new_wallet_info.setWallet_address(t_user_walletModel.getWallet_address());
            new_wallet_info.setAmount(amount);
            new_wallet_info.setStatus("1");
            t_wallet_infoMapper.insert(new_wallet_info);
        }

    }

}

